<!-- Tooltip.vue -->
<template>
    <span @mouseover="showTooltip" @mouseout="hideTooltip" ref="elementRef">
      <slot></slot> <!-- 这里将会插入高亮的专业名词 -->
      <transition name="fade">
        <div class="tooltip" v-if="isShown" :style="{ ...tooltipStyles }">
          <div class="tooltip-content" v-html="definition"></div>
        </div>
      </transition>
    </span>
  </template>
  
  <script setup lang="js">
  import { ref, onMounted, computed } from 'vue';
  
  // 定义默认参数
  const props = defineProps({
    definition: {
      type: String,
      required: true,
    },
  });
  
  const isShown = ref(false);
  let tooltipNodeTop = ref(0);
  let tooltipNodeLeft = ref(0);
  const elementRef = ref(null);
  
  function updatePosition() {
    if (elementRef.value) {
      const rect = elementRef.value.getBoundingClientRect();
      tooltipNodeLeft.value = window.pageXOffset + rect.right + 5; // 调整x轴偏移量
      tooltipNodeTop.value = window.pageYOffset + rect.bottom + 10; // 调整y轴偏移量，并确保相对于屏幕位置固定
    }
  }
  
  onMounted(() => {
    updatePosition();
  
    window.addEventListener('resize', updatePosition);
    window.addEventListener('scroll', updatePosition); // 添加滚动事件监听器以实时更新位置
  });
  
  function showTooltip(event) {
    isShown.value = true;
    console.log("SHOWTOOLTIP");
    updatePosition();
  }
  
  function hideTooltip() {
    isShown.value = false;
  }
  
  const tooltipStyles = computed(() => ({
    position: 'fixed', // 将position更改为fixed
    left: `${tooltipNodeLeft.value}px`,
    top: `${tooltipNodeTop.value}px`,
  }));
  </script>
  
  <style scoped>
  .tooltip {
    position: fixed;
    background-color: #ade0ff; 
    opacity: 0.95;
    padding: 15px 20px;
    border-radius: 10px;
    z-index: 10000;
    white-space: pre-wrap; 
  }
  
  .tooltip-content {
    max-width: 800px;
  }
  
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity .2s;
  }
  
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
  </style>